//
//  MQTextView.swift
//  SinaWeiBo
//
//  Created by 毛强 on 16/1/29.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit

@IBDesignable class MQTextView: UITextView {
    

    override var font:UIFont?{
        didSet{
           placeholderLabel.font = font
        }
        
    }
    @IBInspectable var placeholder:String?{
        didSet{
            placeholderLabel.text = placeholder
        }
    }
    
    override var text:String?{
        didSet{
            placeholderLabel.hidden = self.hasText()
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    private func setupUI(){
        self.backgroundColor = UIColor.whiteColor()
        addSubview(placeholderLabel)
        
        //注册textview文字改变通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewDidChange", name: UITextViewTextDidChangeNotification, object: nil)
    }
    
    //注销通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    @objc private func textViewDidChange(){
        placeholderLabel.hidden = self.hasText()
    }
    private lazy var placeholderLabel:UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.font = UIFont.systemFontOfSize(12)
        label.textColor = UIColor.grayColor()
        return label
    }()

    override func layoutSubviews() {
        super.layoutSubviews()
        placeholderLabel.frame.origin.x = 5
        placeholderLabel.frame.origin.y = 8
       placeholderLabel.frame.size = (placeholderLabel.text! as NSString).boundingRectWithSize(CGSize(width: SCREENW - placeholderLabel.frame.origin.x * 2, height: CGFloat(MAXFLOAT)), options: .UsesLineFragmentOrigin, attributes: [ NSFontAttributeName : placeholderLabel.font], context: nil).size
    }
    
    func textEmoticon() -> String{
        var string : String = ""
        self.attributedText.enumerateAttributesInRange(NSMakeRange(0, self.attributedText.length), options: []) { (dict, range, _) -> Void in
            if let attach = dict["NSAttachment"] as? MQTextAttachment{
                
                //发送图片字符
                string += attach.emoticon!.chs!
                
            }else{
                string += (self.attributedText.string as NSString).substringWithRange(range)
                //发送文字
            }
        }
        return string
    }
}
